package com.zone.vehicle.superapp.view.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageInstaller;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.saic.services.zonestore.ISoaZoneStoreCallBack;
import com.saic.services.zonestore.ISoaZoneStoreService;
import com.saic.services.zonestore.ZoneStoreAppInfo;
import com.zone.lib.download.DownloadConstant;
import com.zone.lib.download.DownloadHelper;
import com.zone.lib.download.db.DownloadDaoUtilsStore;
import com.zone.lib.download.db.entity.Download;
import com.zone.lib.download.enums.AppStatusEnum;
import com.zone.lib.download.install.AndroidP;
import com.zone.lib.download.utils.AppStatusUpdateNotify;
import com.zone.lib.download.utils.DownloadUtil;
import com.zone.lib.download.utils.SharedPreferencesUtil;
import com.zone.sdk.common.http.base.Result;
import com.zone.sdk.common.http.callback.ResultCallBack;
import com.zone.sdk.module.appstore.entity.AppDetailEntity;
import com.zone.sdk.module.appstore.request.AppsDetailRequest;
import com.zone.sdk_api.ApiManager;
import com.zone.vehicle.superapp.model.SuperAppServiceModel;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.atomic.AtomicBoolean;

import static com.zone.sdk_api.common.Content.VIN;

public class SupperService extends Service {

    private static final String TAG = SupperService.class.getSimpleName();
    private static final String TAG_VAL_PUSH_MESSAGE = "val-push-message ";

    private AtomicBoolean threadFlag = new AtomicBoolean(false);
    private MyThread mThread;
    private SuperServiceBinder binder = new SuperServiceBinder();

    public SupperService() {
    }

    public class SuperServiceBinder extends Binder {
        public SupperService getService() {
            return SupperService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Context context = this;
        startThread();
        registerReceiver();
        initIDigitalZoneStoreService();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy, Thread: " + Thread.currentThread().getName());
        super.onDestroy();
        stopThread();
        unregisterReceiver();
        stopOfferService();
    }

    public void reStartDigitalService() {
        Log.d(TAG, "reStartDigitalService");
        unregisterReceiver();
        stopOfferService();
        registerReceiver();
        initIDigitalZoneStoreService();
    }

    private void startThread() {
        threadFlag.set(true);
        mThread = new MyThread();
        mThread.start();
    }

    private void stopThread() {
        threadFlag.set(false);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind Thread: " + Thread.currentThread().getName());
        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "onUnbind from:" + intent.getStringExtra("from"));
        return super.onUnbind(intent);
    }

    public class MyThread extends Thread {
        @Override
        public void run() {
            super.run();
            // TODO runtime
            while (threadFlag.get()) {
                Log.d(TAG, "Thread supper service running!");
                try {
                    Thread.sleep(1000 * 60);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
//        filter.addAction(Constants.INSTALL_INTENT_ACTION);
        filter.addAction(AndroidP.ACTION_INSTALL);
        filter.addAction(AndroidP.ACTION_UNINSTALL);
        filter.addAction(DownloadConstant.REFRESH_TASK);
        filter.addAction(DownloadConstant.JD_ACTION_INSTALL);
        registerReceiver(receiver, filter);
        Log.d(TAG, "start register receiver");
    }

    private void unregisterReceiver() {
        try {
            Log.d(TAG, "start unregister receiver");
            unregisterReceiver(receiver);
        } catch (IllegalArgumentException e) {
            Log.e(TAG, e.toString());
        }

    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive=" + intent.getAction());
            if (null != intent.getAction()) {
                String code = null;
                switch (intent.getAction()) {
//                    case Constants.INSTALL_INTENT_ACTION:
//                        //APP安装状态 status=1成功
//                        int status = intent.getIntExtra(Constants.INSTALL_INTENT_EXTRA, -1);
//                        try {
//                            code = intent.getStringExtra("code");
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                        Log.d(TAG, "receive install code=" + code + " status=" + (status == 1));
//                        if (StringUtils.isNotEmpty(code)) {
//                            Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(code);
//                            if (ObjectUtils.isNotEmpty(download)) {
//                                download.setDownloadStatus(status == 1 ? AppStatusEnum.INSTALL_SUCCESS.CODE : AppStatusEnum.INSTALL_FAIL.CODE);
//                                AppStatusUpdateNotify.appNotify(context, download);
//                            }
//                        }
//                        break;
                    case AndroidP.ACTION_INSTALL:
                        int install_status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE);
                        Log.d(TAG, "install-status="+install_status);
                        try {
                            code = intent.getStringExtra("code");
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        if (StringUtils.isNotEmpty(code)) {
                            Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(code);
                            if (ObjectUtils.isNotEmpty(download)) {
                                download.setDownloadStatus(install_status == PackageInstaller.STATUS_SUCCESS ? AppStatusEnum.INSTALL_SUCCESS.CODE : AppStatusEnum.INSTALL_FAIL.CODE);
                                AppStatusUpdateNotify.appNotify(context, download);
                            }
                        }
                        break;
                    case AndroidP.ACTION_UNINSTALL:
                        int uninstall_status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE);
                        Log.d(TAG, "uninstall-status="+uninstall_status);
                        try {
                            code = intent.getStringExtra("code");
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        if (StringUtils.isNotEmpty(code)) {
                            Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(code);
                            if (ObjectUtils.isNotEmpty(download)) {
                                download.setDownloadStatus(uninstall_status == PackageInstaller.STATUS_SUCCESS ? AppStatusEnum.UNINSTALL_APP_SUCCESS.CODE : AppStatusEnum.UNINSTALL_APP_FAILED.CODE);
                                AppStatusUpdateNotify.appNotify(context, download);
                                if (uninstall_status == PackageInstaller.STATUS_SUCCESS){
                                    DownloadDaoUtilsStore.getInstance().deleteByCode(code);
                                }
                            }
                        }
                        break;
                    case DownloadConstant.REFRESH_TASK:
                        DownloadHelper.getInstance().refreshTask(context);
                        break;
                    case DownloadConstant.JD_ACTION_INSTALL:
                        String event = intent.getStringExtra("event");
                        String appId = intent.getStringExtra("appId");
                        String appType = intent.getStringExtra("appType");
                        Log.d(TAG, "JD-install 0 receive install event=" + event + " appId=" + appId + " appType=" + appType);
                        Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(appId);
                        if (StringUtils.isNotEmpty(event) && event.equals(DownloadConstant.JD_EVENT_DOWNLOADED)) {
                            //小程序安装成功
                            if (ObjectUtils.isNotEmpty(download)) {
                                download.setDownloadStatus(AppStatusEnum.INSTALL_SUCCESS.CODE);
                                AppStatusUpdateNotify.appNotifyWithoutDownload(context, download);
                            } else {
                                AppsDetailRequest request = new AppsDetailRequest();
                                request.setSpuId(appId);
                                request.setVin(SharedPreferencesUtil.getInstance(context).getSP(VIN));
                                request.setUserId(SharedPreferencesUtil.getInstance(context).getUserId(context));
                                ApiManager.getInstance().appsDetail(request, new ResultCallBack<Result<AppDetailEntity>>() {
                                    @Override
                                    public void onSuccess(Result<AppDetailEntity> result) {
                                        if (result.getResultCode().equals("200")) {
                                            Download download = DownloadUtil.build(AppStatusEnum.INSTALL_SUCCESS.CODE, result.getData(), null);
                                            AppStatusUpdateNotify.appNotifyWithoutDownload(context, download);
                                        }
                                    }

                                    @Override
                                    public void onError(String errorCode, String message) {
                                    }

                                    @Override
                                    public void onComplete() {
                                    }
                                });
                            }
                        } else if (StringUtils.isNotEmpty(event) && event.equals(DownloadConstant.JD_EVENT_DELETED)) {
                            if (ObjectUtils.isNotEmpty(download)) {
                                DownloadDaoUtilsStore.getInstance().deleteByCode(appId);
                                download.setDownloadStatus(AppStatusEnum.DOWNLOAD_DELETE.CODE);
                                AppStatusUpdateNotify.appNotify(context, download);
                            }
                        }
                        break;
                }
            }
        }
    };

    /************************************ICM**************************************************/
    private void sendInstallCheckBroadcast(int appStatusEnum, AppDetailEntity appEntity) {
        Log.d(TAG, "sendInstallCheckBroadcast appStatusEnum=" + appStatusEnum);
        Intent intent = new Intent();
//        intent.setAction(DownloadConstant.APP_CHECK_ACTION);
        intent.setAction(DownloadConstant.ACTION_PRE + appStatusEnum);
        intent.putExtra(DownloadConstant.EXTRA_INTENT_APP_STATUS_APP, appEntity);
        sendBroadcast(intent);
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            Log.d(TAG, msg.toString());
            ZoneStoreAppInfo appInfoStruct = (ZoneStoreAppInfo) msg.obj;
            int action = msg.what;
            Log.d(TAG, TAG_VAL_PUSH_MESSAGE + "cloud control action=" + action + " info=" + JSON.toJSONString(appInfoStruct));
            if (action == AppStatusEnum.DOWNLOAD_PREPARE.CODE) {
                SuperAppServiceModel.downloadApp(getApplicationContext(), appInfoStruct.getAppID(), AppStatusEnum.DOWNLOAD_PREPARE);
            } else if (action == AppStatusEnum.UNINSTALL_APP_AND_LIGHT.CODE) {
                SuperAppServiceModel.delete(getApplicationContext(), appInfoStruct.getAppID());
            } else if (action == AppStatusEnum.DOWNLOAD_PAUSE.CODE) {
                SuperAppServiceModel.pauseDownload(getApplicationContext(), appInfoStruct.getAppID());
            } else if (action == AppStatusEnum.DOWNLOAD_CONTINUE.CODE) {
                SuperAppServiceModel.downloadApp(getApplicationContext(), appInfoStruct.getAppID(), AppStatusEnum.DOWNLOAD_PREPARE);
            } else if (action == AppStatusEnum.UPDATE.CODE) {
                SuperAppServiceModel.updateApk(getApplicationContext(), appInfoStruct.getAppID());
            }
            return false;
        }
    });


    /**
     * ICM AIDL 系统消息推送
     */
    protected void initIDigitalZoneStoreService() {
        Log.d(TAG, TAG_VAL_PUSH_MESSAGE + "initIDigitalZoneStoreService");
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.saic.services.zonestore", "com.saic.services.zonestore.ZoneStoreService"));
        try {
            bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            Log.e(TAG, TAG_VAL_PUSH_MESSAGE + "onServiceDisconnected:" + arg0.getPackageName());
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            Log.e(TAG, TAG_VAL_PUSH_MESSAGE + "onServiceConnected:" + name.getPackageName());
            // 获取远程Service的onBinder方法返回的对象代理
            soaZoneStoreService = ISoaZoneStoreService.Stub.asInterface(binder);
            try {
                soaZoneStoreService.offerService();
                soaZoneStoreService.registerZoneStoreCallback(callBack);
            } catch (RemoteException e) {
                Log.e(TAG, e.toString());
            }
        }
    };

    ISoaZoneStoreService soaZoneStoreService = null;

    protected void stopOfferService() {
        if (soaZoneStoreService != null) {
            try {
                soaZoneStoreService.unregisterZoneStoreCallback(callBack);
                soaZoneStoreService.stopOfferService();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        unbindService(mServiceConnection);
    }

    ISoaZoneStoreCallBack callBack = new ISoaZoneStoreCallBack.Stub() {
        @Override
        public String appContinueInfo(ZoneStoreAppInfo appInfo) throws RemoteException {
            Log.d(TAG, TAG_VAL_PUSH_MESSAGE + " aPPContinueInfo=" + JSON.toJSONString(appInfo));
            try {
                Message message = new Message();
                message.what = AppStatusEnum.DOWNLOAD_CONTINUE.CODE;
                message.obj = appInfo;
                handler.sendMessage(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "SUCCESS";
        }

        @Override
        public String appDownloadInfo(ZoneStoreAppInfo appInfo) throws RemoteException {
            try {
                Log.d(TAG, TAG_VAL_PUSH_MESSAGE + "appDownloadInfo====" + JSON.toJSONString(appInfo));
                Message message = new Message();
                message.what = AppStatusEnum.DOWNLOAD_PREPARE.CODE;
                message.obj = appInfo;
                handler.sendMessage(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "SUCCESS";
        }

        @Override
        public String appPauseInfo(ZoneStoreAppInfo appInfo) throws RemoteException {
            Log.d(TAG, TAG_VAL_PUSH_MESSAGE + "appPauseInfo=" + JSON.toJSONString(appInfo));
            try {
                Message message = new Message();
                message.what = AppStatusEnum.DOWNLOAD_PAUSE.CODE;
                message.obj = appInfo;
                handler.sendMessage(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "SUCCESS";
        }

        @Override
        public String appUninstallInfo(ZoneStoreAppInfo appInfo) throws RemoteException {
            Log.d(TAG, TAG_VAL_PUSH_MESSAGE + "appUninstallInfo=" + JSON.toJSONString(appInfo));
            try {
                Message message = new Message();
                message.what = AppStatusEnum.UNINSTALL_APP_AND_LIGHT.CODE;
                message.obj = appInfo;
                handler.sendMessage(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "SUCCESS";
        }

        @Override
        public String appUpdateInfo(ZoneStoreAppInfo appInfo) throws RemoteException {
            Log.d(TAG, TAG_VAL_PUSH_MESSAGE + "appUpdateInfo=" + JSON.toJSONString(appInfo));
            try {
                Message message = new Message();
                message.what = AppStatusEnum.UPDATE.CODE;
                message.obj = appInfo;
                handler.sendMessage(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "SUCCESS";
        }
    };

}